package core.mvc;

import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

/**
 * 请求入口 opid-》modelclass method-》modelclass.method 权限认证
 */
public class Dispatcher extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int opcodeIndex = 1;
	private int methodIndex = 2;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Dispatcher() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		String contextPath = config.getInitParameter("contextPath");
		if (contextPath != null && contextPath.length() > 0) {
			opcodeIndex = 2;
			methodIndex = 3;
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String[] parts = StringUtils.split(request.getRequestURI(), '/');

		response.getWriter().println(parts[opcodeIndex] + "<br/>");
		
		if(parts.length>methodIndex)
			response.getWriter().println(parts[methodIndex] + "<br/>");

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		System.out.println(request.getRequestURI());
		response.getWriter().println(request.getRequestURI());
		response.getWriter().println(request.getContextPath());
		response.getWriter().println(request.getServletPath());
	}

}
